/*
Copyright 2009 David Revell

This file is part of SwiFTP.

SwiFTP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SwiFTP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SwiFTP.  If not, see <http://www.gnu.org/licenses/>.
*/

package lfr.ustc.ftp;

import java.net.InetAddress;

public class CmdPASV extends CmdManager implements Runnable {

	public CmdPASV(SocketManager sessionThread, String input) {
		super(sessionThread);
	}

	public void run() {
		String cantOpen = "502 Couldn't open a port\r\n";
		int port;
		if ((port = sessionThread.onPasv()) == 0) {
			sessionThread.sendInfo(cantOpen);
			return;
		}
		InetAddress addr = sessionThread.getDataSocketPasvIp();

		if (addr == null) {
			sessionThread.sendInfo(cantOpen);
			return;
		}
		if (port < 1) {
			sessionThread.sendInfo(cantOpen);
			return;
		}
		StringBuilder response = new StringBuilder(
				"227 Entering Passive Mode (");
		response.append(addr.getHostAddress().replace('.', ','));
		response.append(",");

		response.append(port / 256);
		response.append(",");
		response.append(port % 256);
		response.append(").\r\n");
		String responseString = response.toString();
		sessionThread.sendInfo(responseString);
	}
}
